
package cup.modules.visual.service.impl;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import cup.core.log.exception.ServiceException;
import cup.core.mp.base.BaseServiceImpl;
import cup.core.secure.CupUser;
import cup.core.secure.utils.AuthUtil;
import cup.core.tool.utils.BeanUtil;
import cup.core.tool.utils.PlaceholderUtil;
import cup.modules.system.service.IDsService;
import cup.modules.visual.dto.VisualDbDTO;
import cup.modules.visual.dynamic.DynamicDataSourceHelper;
import cup.modules.visual.dynamic.DynamicDataSourceHolder;
import cup.modules.visual.entity.VisualDb;
import cup.modules.visual.mapper.VisualDbMapper;
import cup.modules.visual.service.IVisualDbService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * 可视化数据源配置表 服务实现类
 *
 *
 */
@Service
@AllArgsConstructor
public class VisualDbServiceImpl extends BaseServiceImpl<VisualDbMapper, VisualDb> implements IVisualDbService {

	private final VisualDbMapper mapper;
	private final DynamicDataSourceHolder holder;
	private final DynamicDataSourceHelper dynamicDataSourceHelper;

	private final IDsService sysClient;

	@Override
	public Boolean dbTest(VisualDb db) {
		return dynamicDataSourceHelper.dbTest(db.getDriverClass(), db.getUrl(), db.getUsername(), db.getPassword());
	}

	@Override
	public List<VisualDbDTO> dbList() {
		return mapper.dbList();
	}

	@Override
	public List<LinkedHashMap<String, Object>> dynamicQuery(String id, String sql) {
		try {
			//处理自定义数据源
			holder.handleDataSource(id,sysClient);
			//切换数据源
			DynamicDataSourceContextHolder.push(id);
			//获取user信息
			CupUser user = AuthUtil.getUser();
			//替换user占位符
			String dynamicSql = PlaceholderUtil.getDefaultResolver().resolveByMap(sql, BeanUtil.toMap(user));
			//执行自定义sql
			return mapper.dynamicQuery(dynamicSql);
		} catch (Exception exception) {
			throw new ServiceException(exception.getMessage());
		} finally {
			//切回主数据源
			DynamicDataSourceContextHolder.poll();
		}

	}

}
